package cn.com.pinche.dao.user.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;

import cn.com.pinche.dao.user.UserDao;
import cn.com.pinche.po.User;
import cn.com.pinche.util.UserRowMapper;

public class UserDaoImpl implements UserDao {

	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	public boolean saveUser(User user) {
		
		List<Object> params = new ArrayList<Object>();
		String sql = "insert into testUser(username, password, age) values(?, ?, ?)";
		
		params.add(user.getUsername());
		params.add(user.getPassword());
		params.add(user.getAge());
		
		int affectNum = jdbcTemplate.update(sql, params.toArray());
		
		if(affectNum > 0) {
			return true;
		} 
		return false;
	}
	
	public boolean deleteUser(String id) {
		
		String sql = "delete from testUser where id = ?";
		
		int affectNum = jdbcTemplate.update(sql, new Object[]{id});
		
		if(affectNum > 0) {
			return true;
		} 
		return false;
	}

	public User updateUser(User user) {
		
		String sql = "update testUser set username = ?, password = ?, age = ? where id = ?";
		
		List<Object> params = new ArrayList<Object>();
		
		params.add(user.getUsername());
		params.add(user.getPassword());
		params.add(user.getAge());
		params.add(user.getId());
		
		int affectNum = jdbcTemplate.update(sql, params.toArray());
		
		if(affectNum > 0) {
			return user;
		} 
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> findAllUser() {
		
		String sql = "select * from testUser";
		
		List<User> users = jdbcTemplate.query(sql, new UserRowMapper());
		
		return users;
	}

	public User getUserInfo(String userId) {
		
		String sql = "select * from testUser where id = ?";
		
		return (User)jdbcTemplate.queryForObject(sql, new Object[]{ userId }, new UserRowMapper());
	}
	
}
